.NET Portable TypeCast  3.1.0.4
A, easy-to-use tested, generic, portable, runtime-extensible, arbitrary type converter library
ObjectExtension[Convert].cs
Go to the documentation of this file.
1 // <copyright file=mitlicense.md url=http://lsauer.mit-license.org/ >
2 // Lo Sauer, 2013-2016
3 // </copyright>
4 // <summary> A tested, generic, portable, runtime-extensible type converter library </summary
5 // <language> C# > 6.0 </language>
6 // <version> 3.1.0.2 </version>
7 // <author> Lorenz Lo Sauer; people credited in the sources </author>
8 // <project> https://github.com/lsauer/dotnet-portable-type-cast </project>
9 namespace Core.TypeCast
10 {
11  using System;
12  using System.Reflection;
13  using System.Linq;
14  using System.Runtime.CompilerServices;
15 
16  using Core.TypeCast.Base;
17  using Core.Extensions;
18 
20  public static partial class ObjectExtension
21  {
54  [MethodImpl(MethodImplOptions.AggressiveInlining)]
55  public static TOut ConvertTo<TIn, TOut>(this TIn self, object model, bool withContext = false)
56  {
57  TOut result = default(TOut);
58  self.TryConvert<TOut>(out result, model, throwException: model != null, withContext: withContext);
59  return result;
60  }
61 
92  [MethodImpl(MethodImplOptions.AggressiveInlining)]
93  public static TOut ConvertTo<TOut>(this object self, object model, bool withContext = false)
94  {
95  TOut result = default(TOut);
96  self.TryConvert<TOut>(out result, model, throwException: model != null, withContext: withContext);
97  return result;
98  }
99 
100 
124  public static bool TryConvert<TOut>(this object self, out TOut result, object model, bool throwException = false, bool withContext = false)
125  {
126  Converter converter;
127  result = default(TOut);
128  if(GetConverterOrDefault<object, TOut>(self, out converter, out result, typeArgument: model?.GetType(), throwException: throwException, unboxObjectType: true, withContext: withContext))
129  {
130  return true;
131  }
132 
133  return InvokeConvert(self, out result, model, throwException, converter, contextInstance: (withContext ? new ConvertContext(model) : null));
134  }
135 
161  public static bool TryConvert<TIn, TOut, TArg>(this TIn self, out TOut result, TArg model, bool throwException = false, bool withContext = false)
162  {
163  Converter converter;
164  result = default(TOut);
165  if(GetConverterOrDefault<TIn, TOut>(self, out converter, out result, typeArgument: typeof(TArg), throwException: throwException, unboxObjectType: false, withContext: withContext))
166  {
167  return true;
168  }
169 
170  return InvokeConvert(self, out result, model, throwException, converter, contextInstance: (withContext ? new ConvertContext(model) : null));
171  }
172  }
173 }